<?php

include_once "Model.php";
include_once "User2Track.php";

class Track_ extends Model {
  private $mb; 
  
  public function Track_($attr=null){ 
  	
    $this->table_name = TRACK_TABLE; parent::__construct($attr);
    $this->mb = new MusicBrainz();
  }
  
  public function add(){
      
    $this->attributes['time_added'] = 'NOW()';
    //this will return give a value to $this->id
    parent::add();
    //add the track2user entry
    $user2track = new User2Track_(array(user_id=>Session::factory()->getUserId(),track_id=>$this->id));
    $user2track->add();
    
    return $this->id;
  }
  
  public function deleteFull(){
  	parent::delete();
    $user2track = new User2Track_(array(user_id=>Session::factory()->getUserId(),user_id=>$this->id));
    $user2track->delete();
  }
  
  public function getDetails(){
  	$q = "SELECT t.url,t.artist_id, t.rating,t.id,t.played_times,t.mb_id AS track_mb_id,t.mood,t.title,t.time_added,a.name AS artist, a.picture, a.mb_id AS artist_mb_id,r.id AS release_id, r.title AS release_title, r.mb_id AS release_mb_id, r.coverimage, user.id AS uid,user.name AS submitter,user.fb_id AS fb_submitter,ar.body,COUNT(u2f.user_id) AS favs,u2f_.user_id AS fav_user
          FROM (".TRACK_TABLE." t, ".ARTIST_TABLE." a, ".USER_TABLE." user)
          LEFT JOIN ".RELEASE_TABLE." r ON (t.release_id = r.id) 
          LEFT JOIN ".ARTICLE_TABLE." ar ON (ar.track_id=t.id) 
          LEFT JOIN ".USER2FAV_TABLE." u2f ON (t.id = u2f.track_id)
          LEFT JOIN ".USER2FAV_TABLE." u2f_ ON (t.id = u2f_.track_id AND ".Session::factory()->getUserId()." = u2f_.user_id )
          WHERE t.id ={$this->attributes['id']}
          AND t.artist_id = a.id
          AND user.id = (
            SELECT user_id
            FROM ".USER2TRACK_TABLE."
            WHERE track_id = t.id 
          )
          GROUP BY u2f.track_id";
    //echo $query;      
    return $this->SQL->query($q)->fetchObject();
  }
}

?>
